<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :append-to-body="true"
      :title="title"
      align="center"
      :before-close="handleClose"
      :visible.sync="dialogFormVisible"
      @closed="closedDialog"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        :class="{ en: $i18n.locale === 'en' }"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          v-if="value"
          :label="sysBusinessCategory.categoryParent"
          :label-width="formLabelWidth"
          prop="parentId"
          :error="errorMsg.parentId"
        >
          <BaseTreeSelect
            v-model="formData.parentId"
            :tree-data="categoryTree"
            :disabled="editId != ''"
            :placeholder="sysBusinessCategory.chooseCategory"
            @node-click="handleNodeClick"
          />
        </el-form-item>
        <el-form-item
          :label="sysBusinessCategory.categoryName"
          :label-width="formLabelWidth"
          prop="name"
          :error="errorMsg.name"
        >
          <el-input
            v-model="formData.name"
            autocomplete="off"
            maxlength="50"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessCategory.categoryEName"
          :label-width="formLabelWidth"
          prop="eName"
          :error="errorMsg.eName"
        >
          <el-input
            v-model="formData.eName"
            autocomplete="off"
            maxlength="50"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessCategory.classificationIdentification"
          :label-width="formLabelWidth"
          prop="code"
          :error="errorMsg.code"
        >
          <el-input
            v-model="formData.code"
            autocomplete="off"
            maxlength="50"
            clearable
            :placeholder="sysBusinessCategory.enterLettersNumbersWHP"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessCategory.inspectionBasis"
          :label-width="formLabelWidth"
          prop="inspectionBasis"
          :error="errorMsg.inspectionBasis"
        >
          <el-input
            v-model="formData.inspectionBasis"
            autocomplete="off"
            maxlength="50"
            clearable
            :placeholder="
              sysBusinessCategory.enterInspectionCriteriaVerification
            "
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessCategory.status"
          :label-width="formLabelWidth"
          prop="status"
          :error="errorMsg.status"
        >
          <el-select v-model="formData.status">
            <el-option :label="sysBusinessCategory.enable" :value="1" />
            <el-option :label="sysBusinessCategory.disable" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="sysBusinessCategory.operator"
          :label-width="formLabelWidth"
          prop="operatorName"
        >
          <el-input
            v-model="formData.operatorName"
            autocomplete="off"
            :disabled="true"
            :placeholder="sysBusinessCategory.defaultCurrentLoggedUser"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="sysBusinessCategory.operationTime"
          :label-width="formLabelWidth"
          prop="updateTime"
        >
          <el-input
            v-model="formData.updateTime"
            autocomplete="off"
            :disabled="true"
            :placeholder="sysBusinessCategory.defaultCurrentTime"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button
          type="primary"
          :disabled="!submitLoad"
          @click="onSubmit('formData')"
          >{{ operateType.save }}</el-button
        >
        <el-button @click="handleReset">{{ operateType.resetting }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  create,
  update,
  getById,
  getTreeData,
} from "../../../api/SysBusiness/SysBusinessCategory";
import { formatData } from "../../../utils/index";
import _ from "lodash";
export default {
  name: "SysBusinessCategoryEdit",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [String, Number],
      default: "",
    },
    parentId: {
      type: [String, Number],
      default: "",
    },
    appId: {
      type: [String, Number],
      default: "1000",
    },
  },
  data() {
    return {
      submitLoad: true,
      loading: false,
      dialogFormVisible: false,
      formLabelWidth: "100px",
      title: "",
      categoryTree: [],
      formData: {
        id: 0,
        name: "",
        eName: "",
        code: "",
        status: 1,
        parentId: 0,
        appId: 1000,
        inspectionBasis: "",
      },
      formDataRules: {
        parentId: [
          {
            required: true,
            trigger: "change",
            message: this.$t("SysBusinessCategory.selectParentCategory"),
            type: "",
          },
        ],
        name: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        code: [
          {
            required: false,
            trigger: "blur",
            validator: this.validateAZNumber,
          },
        ],
      },
      initErrorMsg: {
        name: "",
        eName: "",
        status: "",
        parentId: "",
        appId: "",
        inspectionBasis: "",
      },
      errorMsg: {
        name: "",
        eName: "",
        status: "",
        parentId: "",
        appId: "",
        inspectionBasis: "",
      },
    };
  },
  computed: {
    operateType() {
      return this.$t("ModuleSysBusiness.OperateType") || {};
    },
    sysBusinessCategory() {
      return this.$t("SysBusinessCategory") || {};
    },
  },
  watch: {
    value: function() {
      this.dialogFormVisible = this.value;
      if (this.value) {
        this.init();
      }
    },
  },
  methods: {
    async init() {
      await this.getOptions();
      if (this.editId) {
        this.title = this.$t("SysBusinessCategory.editCategory");
        this.formData.id = this.editId;
        getById({ id: this.editId })
          .then((res) => {
            this.formData = res.data ? res.data : {};
          })
          .finally(() => {
            this.formLoading = false;
          });
      } else {
        this.title = this.$t("SysBusinessCategory.addCategory");
        this.formData.id = 0;
        this.formData.appId = this.appId;
        this.formData.parentId = this.parentId;
        this.loading = false;
      }
    },
    getOptions() {
      return new Promise((resolve) => {
        getTreeData({ AppId: this.appId }).then((res) => {
          this.categoryTree = formatData(res.data);
          resolve();
        });
      }).catch();
    },
    handleNodeClick(data, node) {
      if (data.id !== null && data.id.length !== 0) {
        this.formData.parentId = data.id;
      }
    },
    handleReset() {
      if (this.editId) {
        getById({ id: this.editId })
          .then((res) => {
            this.formData = res.data ? res.data : {};
          })
          .finally(() => {
            this.formLoading = false;
          });
      } else {
        this.$refs.formData.resetFields();
        if (this.parentId) {
          this.formData.parentId = this.parentId;
        }
      }
    },
    // 关闭弹框
    handleClose() {
      this.$parent.getList();
      this.closedDialog();
    },
    // 关闭弹框动画结束
    closedDialog() {
      // 动画结束后在清空表单 防止页面闪烁
      this.$refs.formData.resetFields();
      this.$emit("input", false);
      // this.formData = this.$options.data().formData;
      this.$parent.getTree();
    },
    onSubmit: _.throttle(function() {
      if (this.submitLoad) {
        this.submitLoad = false;
        this.$refs.formData.validate((valid) => {
          if (valid) {
            this.loading = true;
            this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
            if (this.editId) {
              update(this.formData)
                .then((res) => {
                  if (res.code === 200) {
                    this.submitLoad = true;
                    this.handleClose();
                  } else {
                    this.submitLoad = true;

                    this.showValidateMsgCheck(res);
                  }
                  this.submitLoad = true;

                  this.loading = false;
                })
                .catch(() => {
                  this.submitLoad = true;

                  this.loading = false;
                });
            } else {
              create(this.formData)
                .then((res) => {
                  if (res.code === 200) {
                    this.submitLoad = true;

                    this.handleClose();
                  } else {
                    this.submitLoad = true;

                    this.showValidateMsgCheck(res);
                  }
                  this.submitLoad = true;

                  this.loading = false;
                })
                .catch(() => {
                  this.submitLoad = true;

                  this.loading = false;
                });
            }
          } else {
            return false;
          }
        });
      }
    }, 2000),
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("name", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("status", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("parentId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("appId", this.errorMsg, res.msg);
      }
    },
    validateAZNumber(rule, value, callback) {
      var regex = new RegExp("^[A-Za-z0-9]+$");
      if (value != null && value !== "" && !regex.test(value)) {
        callback(new Error(this.$t("SysBusinessCategory.mustLettersNumbers")));
      } else {
        callback();
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.base-pipeline-layout {
  &.en {
    ::v-deep .el-form-item {
      .el-form-item__label {
        word-break: break-word;
      }
    }
  }
}
</style>
